//
//  RefreshTableView.m
//  GlobayPaySimplify
//
//  Created by Epay on 15/5/7.
//  Copyright (c) 2015年 Epaylinks. All rights reserved.
//

#import "RefreshTableView.h"
#import "MJRefresh.h"
#import "ChatHeader.h"

@implementation RefreshTableView
- (instancetype)initWithDelegate:(id)refDelegate andStyle:(UITableViewStyle)style andTradeType:(NSUInteger)type{
    self = [super initWithFrame:CGRectZero style:style];
    if (self) {
        if (refDelegate && [refDelegate respondsToSelector:@selector(pullDownDataWithType:)]) {
            self.tradeType = type;
            // 初次创建只有［全部］标签加载全部数据
            if (0 == self.tradeType) {
                [refDelegate pullDownDataWithType:self.tradeType];
            }
            [self loadView];
        }
    }
    return self;
}

- (void)loadView{
    self.frame = CGRectMake(0, 0, kWidth, kHeight-44-20);
    //集成刷新控件
    [self setupRefresh];
}


- (void)setupRefresh{
    [self addHeaderWithType:self.tradeType];
    [self addFooterWithType:self.tradeType];
}

#pragma mark - 添加头部
- (void)addHeaderWithType:(NSUInteger)type{
    //添加数据
    MJRefreshNormalHeader *headerView = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.refreshDeleage && [self.refreshDeleage respondsToSelector:@selector(pullDownDataWithType:)]) {
            [self.refreshDeleage pullDownDataWithType:self.tradeType];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //刷新表格
            [self reloadData];
            //(最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.mj_header endRefreshing];
        });
        
    }];
    self.mj_header = headerView;
}

#pragma mark - 添加尾部
- (void)addFooterWithType:(NSUInteger)type{
    MJRefreshAutoNormalFooter *footerView = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //添加数据
        if (self.refreshDeleage && [self.refreshDeleage respondsToSelector:@selector(pullUpDataWithType:)]) {
            _haveNewData = [self.refreshDeleage pullUpDataWithType:type];
        }
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //刷新表格
            [self reloadData];
            //(最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.mj_footer endRefreshing];
            
        });
    }];
    self.mj_footer = footerView;
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
